package com.itqf.relam;



import com.itqf.entity.User;
import com.itqf.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 作者:高少东
 * 项目名:  product_gsd
 * 时间: 2019/12/19 9:35
 * 描述:
 */

@Component
public class UserRelam extends AuthorizingRealm {


    @Autowired
    UserService userService;

    {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("SHA-256");
        matcher.setHashIterations(1024);
        this.setCredentialsMatcher(matcher);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {


        User user = (User) principalCollection.getPrimaryPrincipal();

        Set<String> roles = userService.selectRoleByAccount(user.getUAccount());

        Set<String> permission = userService.selectPermissionByRole(roles);

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permission);
        return authorizationInfo;
    }


    /**
     *
     * @param authenticationToken    查询账号是否存在  ,存在比对密码
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {


        String account = (String) authenticationToken.getPrincipal();

        User user =userService.loginAccount(account);

        if (user==null){

            return null;
        }else {

            String uSalt = user.getUSalt();

            ByteSource salt = ByteSource.Util.bytes(uSalt);

            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user,user.getUPassword(),salt,this.getName());

            return  authenticationInfo;
        }


    }
}
